<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Json格式化</title>
</head>
<style>
    * {
        margin: 0;
        padding: 0;
        font-size: 18px;
    }

    body {
        margin: 0 auto;
        width: 900px;
        height: 800px;
        align-content: center;
    }

    .container {
        display: flex;
        flex-direction: column;
        justify-content: start;
        align-items: center;
        width: 100%;
        height: 100%;
    }


</style>
<body>
<div class="container">
    <label for="json">数据：<textarea id="json" rows="15" cols="100"></textarea></label>
    <div style="width:100%;"><label for="res">结果：</label><label>间隔：<input id="space" type="number" value="4" min="0" max="10"/></label></div>
    <textarea id="res" rows="20" cols="100"></textarea>
</div>
<script>
    function onload() {
        let json = document.getElementById("json")
        let res = document.getElementById("res")
        let space = document.getElementById("space")
        json.addEventListener("input", function () {
            if (json.value === "") {
                res.value = ""
                return;
            }
            try {
                res.value = JSON.stringify(JSON.parse(json.value), (k,v)=>{
                    if(k===""){
                        console.log("root")
                    }
                    if(typeof(v)==="object"){
                        console.log(`<p>对象：${v}</p>`)
                    }
                    console.log(k,v)
                    return v;
                }, parseInt(this.value))
            } catch (e) {
                res.value = e.message
            }
        })
        space.addEventListener("change", function () {
            if (json.value === "") {
                res.value = ""
                return;
            }
            try {
                res.value = JSON.stringify(JSON.parse(json.value), null, parseInt(this.value))
            } catch (e) {
                res.value = e.message
            }
        })
    }

    window.addEventListener("load", onload)
</script>
</body>
</html>